package interaction

import (
	"strconv"
	"strings"
	"time"

	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/app/sysparam"

	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/columnd"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/util"

	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/common"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/interactiond"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/ddd"
)

type reqColl struct {
	TargetID   string                    `json:"target_id"`   //　目标
	TargetType interactiond.IGTargetType `json:"target_type"` // 　类型
}
type respColl struct {
	ID         string                    `json:"id"`          // 互动ｉｄ
	IGID       string                    `json:"igid"`        // 互动组ID
	TargetID   string                    `json:"target_id"`   //　目标
	TargetType interactiond.IGTargetType `json:"target_type"` // 　类型
	UID        string                    `json:"uid"`         // 互动用户
	Kind       int                       `json:"kind"`        // 类型　1 信息，2互动
	Title      string                    `json:"title"`       // 标题
	URL        string                    `json:"url"`         // 跳转明细链接
	Content    string                    `json:"content"`     // 收藏内容
	ListMode   int                       `json:"list_mode"`   // 列表模式
	Imgs       []string                  `json:"imgs"`        // 图片列表
	Viedo      string                    `json:"viedo"`       // 视频网址
	Tag        string                    `json:"tag"`         // 标签　信息为栏目名称　互动为Tags 中的第一个值
	// ReplayNum  int                       `json:"replay_num"`  // 评论数量
	// IsLike     int                       `json:"is_like"`     // 是否可以点赞 0 不可以点赞，１　可以点赞
	// LikeNum    int                       `json:"like_num"`    // 点赞数量
	// MyLike     bool                      `json:"my_like"`     // 我是否点赞 false 否　true 是
	CollTime time.Time `json:"coll_time"` // 收藏时间
	PubTime  time.Time `json:"pub_time"`  // 发布时间
}

func (c interactionCtrl) putColl(ctx *gin.Context) {
	code := sysparam.IntsCollectionCode()

	iityp, id, err := getTypAndID(ctx)
	if err != nil {
		c.ErrBadRequest(ctx, 1, "参数错误", err)
		return
	}
	dctx := c.DDDContext(ctx)
	uid := dctx.UID()
	if uid == "" {
		c.ErrUnauthorized(ctx, "保存失败：未登录")
		return
	}
	if err = c.addOp(dctx, uid, code, reqOp{
		TargetID:   id,
		TargetType: iityp,
		Value:      1,
	}); err != nil {
		c.ErrServerError(ctx, 6, "收藏失败", err)
		return
	}
	c.Success(ctx, nil)
}
func (c interactionCtrl) deleteColl(ctx *gin.Context) {
	code := sysparam.IntsCollectionCode()

	iityp, id, err := getTypAndID(ctx)
	if err != nil {
		c.ErrBadRequest(ctx, 1, "参数错误", err)
		return
	}

	dctx := c.DDDContext(ctx)
	uid := dctx.UID()
	if uid == "" {
		c.ErrUnauthorized(ctx, "取消收藏失败：未登录")
		return
	}
	if err := c.deleteOp(dctx, uid, code, reqOp{
		TargetID:   id,
		TargetType: iityp,
	}); err != nil {
		c.ErrServerError(ctx, 5, "取消收藏失败", errors.Wrapf(err, "取消收藏失败"))
		return
	}
	c.Success(ctx, nil)
}
func getTypAndID(ctx *gin.Context) (iityp interactiond.IGTargetType, id string, err error) {
	typ := ctx.Param("typ")

	if typ == "" {
		err = errors.New("参数错误：类型定义错误")
		return
	}
	ityp, err := strconv.Atoi(typ)
	if err != nil {
		err = errors.New("取消收藏失败:参数错误")
		return
	}
	iityp = interactiond.IGTargetType(ityp)
	id = ctx.Param("id")
	if typ == "" {
		err = errors.New("取消收藏失败:参数错误")
		return
	}
	return
}
func (c interactionCtrl) queryPageMyColl(ctx *gin.Context) {

	code := sysparam.IntsCollectionCode()
	sch := c.getOpSearch(ctx)
	sch.Codes = []string{code}
	dctx := c.DDDContext(ctx)
	uid := dctx.UID()
	if uid == "" {
		c.ErrUnauthorized(ctx, "保存失败：未登录")
		return
	}
	sch.UID = []string{uid}
	c.queryPageColls(ctx, dctx, sch)
}
func (c interactionCtrl) queryPageColls(ctx *gin.Context, dctx ddd.Context, sch interactiond.InteractionSearch) {
	page := c.GetPageInfo(ctx, common.PageModeID)
	pr, cs, err := c.iiar.QueryPage(dctx, sch, page)
	if err != nil {
		c.ErrServerError(ctx, 30, "查询失败", errors.Wrapf(err, "查询互动交互列表失败"))
		return
	}
	out := make([]respColl, 0, len(cs))
	//uid := dctx.UID()
	for _, v := range cs {

		typ := v.IGID[0:3]
		ityp, err := strconv.Atoi(typ)
		if err != nil {
			ityp = 1
		}
		targetID := v.IGID[4:]
		rc := respColl{
			ID:         v.InteractionID,
			IGID:       v.IGID,
			UID:        v.UID,
			CollTime:   v.CreTime,
			TargetType: interactiond.IGTargetType(ityp),
			TargetID:   targetID,
		}
		if rc.TargetType == interactiond.IGTTInfo {
			// 查询信息
			i, err := c.iar.GetInfo(dctx, targetID)
			if err != nil {
				c.ErrServerError(ctx, 31, "查询失败", errors.Wrapf(err, "查询收藏对应的信息(%v)失败", targetID))
				return
			}
			if i == nil {
				continue
			}
			// 获取栏目信息
			col, err := c.car.GetColumn(dctx, i.ColumnID)
			if err != nil {
				c.ErrServerError(ctx, 32, "查询失败", errors.Wrapf(err, "查询收藏对应的信息(%v)的栏目(%v)失败", targetID, i.ColumnID))
				return
			}

			switch col.Kind {
			case columnd.ColumnKindInteractive:
				rc.Kind = 2
				if i.Tags != nil && len(i.Tags) > 0 {
					rc.Tag = i.Tags[0]
				}
				if sp, ok := i.Extras["sp"]; ok {
					switch v := sp.(type) {
					case string:
						rc.Viedo = v
					default:
					}
				}
				if col.Infourl == "" {
					rc.URL = "/interaction_detail/:columnid/:infoid"
				} else {
					rc.URL = col.Infourl
				}

				rc.URL = strings.Replace(rc.URL, ":infoid", i.InfoID, -1)
				rc.URL = strings.Replace(rc.URL, ":columnid", i.ColumnID, -1)
			default:
				rc.Kind = 1
				rc.Tag = col.Name
				if col.Infourl == "" {
					rc.URL = "/common_detail/:infoid"
				} else {
					rc.URL = col.Infourl
				}
				rc.URL = strings.Replace(rc.URL, ":infoid", i.InfoID, -1)
			}
			rc.Title = i.Title
			rc.Content = util.SubStringForUnicode(i.Content, 0, 100)
			rc.Imgs = i.Icon
			rc.PubTime = i.PublishTime
		}
		// // 获取互动组信息
		// g, err := c.igar.GetGroup(dctx, v.IGID)
		// if err != nil {
		// 	c.ErrServerError(ctx, 33, "查询失败", errors.Wrapf(err, "查询互动组(%v)失败.", v.IGID))
		// 	return
		// }
		// if g != nil {
		// 	rc.ReplayNum = g.ReplayNum
		// 	// 是否可以点赞
		// 	rc.IsLike = isExistsForArray(g.AllowCodes, intTypeLikeCode)
		// 	if rc.IsLike == 1 {
		// 		for _, v := range g.GroupTotal {
		// 			if v.ITCode == intTypeLikeCode {
		// 				rc.LikeNum = v.TotalScore
		// 				break
		// 			}
		// 		}
		// 	}
		// }
		// // 获取我有没有点赞
		// _, rs, err := c.iiar.QueryPage(dctx, interactiond.InteractionSearch{
		// 	IGID:  []string{v.IGID},
		// 	UID:   []string{uid},
		// 	Codes: []string{intTypeLikeCode},
		// }, common.PageInfo{})
		// if err != nil {
		// 	c.ErrServerError(ctx, 34, "查询失败", errors.Wrapf(err, "查询互动组(%v)是否已经点赞失败.", v.IGID))
		// 	return
		// }
		// if len(rs) > 0 {
		// 	rc.MyLike = true
		// }
		out = append(out, rc)
	}
	c.SuccessPage(ctx, page, pr, out)
}

func isExistsForArray(codes []string, code string) int {
	for _, v := range codes {
		if v == code {
			return 1
		}
	}
	return 0
}
